package initialize

import (
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	"gorm.io/gorm/logger"
	"gorm.io/gorm/schema"
)

// 安装包：
// 1.go get -u gorm.io/gorm
// 2.go get -u gorm.io/driver/sqlite
// 3.go get -u gorm.io/driver/mysql

var DefaultDbConnHandler *gorm.DB

// MysqlInit 初始化数据库
func MysqlInit() {
	hostName := Env("mysql", "DB_HOST").Value()
	hostPort := Env("mysql", "DB_PORT").Value()
	database := Env("mysql", "DB_DATABASE").Value()
	username := Env("mysql", "DB_USERNAME").Value()
	password := Env("mysql", "DB_PASSWORD").Value()
	charset := Env("mysql", "DB_CHARSET").Value()
	prefix := Env("mysql", "DB_PREFIX").Value()
	//多个数据库连接可以新增
	dsn := username + ":" + password + "@tcp(" + hostName + ":" + hostPort + ")/" + database + "?charset=" + charset + "&parseTime=True&loc=Local"

	defaultDb, err := gorm.Open(mysql.Open(dsn), &gorm.Config{
		NamingStrategy: schema.NamingStrategy{
			TablePrefix:   prefix, // 设置表前缀
			SingularTable: true,   // 使用单数表名
		},
		Logger: logger.Default.LogMode(logger.Info),
	})

	if err != nil {
		panic("数据库初始化失败：" + err.Error())
	}
	sqlDB, _ := defaultDb.DB()
	sqlDB.SetMaxIdleConns(10)
	sqlDB.SetMaxOpenConns(100)

	DefaultDbConnHandler = defaultDb

	return
}

func YrDbConnect() *gorm.DB {
	return DefaultDbConnHandler
}

func ZyDbConnect() {

}
